package com.youhome.service.service.impl;


import com.youhome.common.config.USAConfig;
import com.youhome.common.exception.CustomException;
import com.youhome.common.response.Result;
import com.youhome.common.response.ResultCode;
import com.youhome.service.mapper.CityDataMapper;
import com.youhome.service.model.CityData;
import com.youhome.service.model.Zip;
import com.youhome.service.response.ThreePlacesValue;
import com.youhome.service.service.CityDataService;
import com.youhome.service.service.UnemploymentService;
import com.youhome.service.service.ZipService;
import com.youhome.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by chen365 on 2017/9/11.
 */
@Service
public class CityDataServiceImpl implements CityDataService {
    @Autowired
    private ZipService zipService;
    @Autowired
    private UnemploymentService unemploymentService;
    @Autowired
    private CityDataMapper cityDataMapper;
    @Autowired
    private USAConfig usaConfig;

    @Override
    public CityData selectByZipcode(String zipcode) throws Exception {
        return cityDataMapper.selectByZipcode(zipcode);
    }

    @Override
    public ThreePlacesValue selectUnemployedByZip(String zip) throws CustomException {

        if (StringUtils.isEmpty(zip)) {
            throw new CustomException(ResultCode.EMPTY_PARAM);
        }

        CityData cityData = cityDataMapper.selectByZipcode(zip);
        if (cityData != null) {
            throw new CustomException(ResultCode.NO_DATA_WAS_FOUND);
        }
        Zip entity = zipService.selectByPrimaryKey(zip);
        if (entity == null) {
            throw new CustomException(ResultCode.EMPTY_ZIP);
        }
        String state = entity.getState();
        if (StringUtils.isEmpty(state)) {
            throw new CustomException(ResultCode.STATE_NULL);
        }
        Double state_unemployed_rate = unemploymentService.selectRateByUnemployment(1, state);

        ThreePlacesValue threePlacesValue = new ThreePlacesValue();
        //本地失业率
        threePlacesValue.setLocal(cityData.getUnemployed());
        //州失业率
        if (state_unemployed_rate != null) {
            threePlacesValue.setState(state_unemployed_rate);
        }
        //全美失业率
        threePlacesValue.setAll(usaConfig.getUnemployed());
        return threePlacesValue;
    }
}
